package com.fili.gui;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: fili
 * Date: Sep 24, 2006
 * Time: 8:53:33 PM
 * To change this template use File | Settings | File Templates.
 */
public class ActionsEngine
{
    private HashMap<Enum, Action> actions = new HashMap<Enum, Action>();
    private Object actionHandler;
    Method[] methods;

    public ActionsEngine(Object actionHandler)
    {
        this.actionHandler = actionHandler;
        methods = actionHandler.getClass().getMethods();
    }

    public void setAction(final Enum anEnum, final String name, ImageIcon icon)
    {
        actions.put(anEnum, new AbstractAction(name, icon)
        {

            {
                putValue(Action.SHORT_DESCRIPTION, name);
            }

            public void actionPerformed(ActionEvent e)
            {
                for (Method method : methods)
                {
                    if (method.getName().compareTo("do_" + anEnum.name()) == 0)
                    {
                        try
                        {
                            method.invoke(actionHandler);
                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }

                        break;
                    }
                }
            }
        });
    }

    public void setAction(final Enum anEnum, final String name, ImageIcon icon, final KeyStroke keyStroke)
    {
        actions.put(anEnum, new AbstractAction(name, icon)
        {

            {
                putValue(Action.SHORT_DESCRIPTION, name);
                putValue(Action.ACCELERATOR_KEY, keyStroke);
            }

            public void actionPerformed(ActionEvent e)
            {
                for (Method method : methods)
                {
                    if (method.getName().compareTo("do_" + anEnum.name()) == 0)
                    {
                        try
                        {
                            method.invoke(actionHandler);
                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }

                        break;
                    }
                }
            }
        });
    }


    public Action getAction(Enum anEnum)
    {
        return actions.get(anEnum);
    }

    public void doAction(Enum anEnum)
    {
        actions.get(anEnum).actionPerformed(null);
    }

}
